package com.b2c.erp.controller.shop.tao;


import com.b2c.entity.api.ApiResult;
import com.b2c.entity.api.ApiResultEnum;
import com.b2c.entity.datacenter.DcTmallOrderEntity;
import com.b2c.entity.datacenter.DcTmallOrderItemEntity;
import com.b2c.entity.result.ResultVo;
import com.b2c.entity.enums.EnumShopType;
import com.b2c.entity.enums.third.EnumTmallOrderStatus;
import com.b2c.erp.DataConfigObject;
import com.b2c.erp.controller.CommonControllerUtils;
import com.b2c.erp.controller.order.erp.OrderConfirmReq;
import com.b2c.interfaces.ExpressCompanyService;
import com.b2c.interfaces.ShopService;
import com.b2c.interfaces.WmsUserService;
import com.b2c.interfaces.erp.ErpGoodsService;
import com.b2c.interfaces.tao.DcTmallOrderService;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFPatriarch;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import javax.swing.JOptionPane;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
* 淘系 订单管理
*/
@RequestMapping("/tao")
@Controller
public class TaoOrderController {
   @Autowired
   private DcTmallOrderService tmallOrderService;
   @Autowired
   private ShopService shopService;
   @Autowired
   private ExpressCompanyService expressCompanyService;
   @Autowired
   private ErpGoodsService erpGoodsService;
    @Autowired
    private WmsUserService manageUserService;
   private static Logger log = LoggerFactory.getLogger(TaoOrderController.class);
   /**
    * 订单列表
    *
    * @param model
    * @param shopId
    * @param request
    * @return
    */
   @RequestMapping("/order_list")
   public String orderList(Model model, @RequestParam Integer shopId, HttpServletRequest request) {
       //查询店铺信息
       var shop = shopService.getShop(shopId);
       if (shop.getType().intValue() != EnumShopType.Tmall.getIndex()) {
           //并不是淘宝开放平台店铺
           return "redirect:/";
       }

       model.addAttribute("shopId", shopId);
       model.addAttribute("shop", shop);
       model.addAttribute("menuId", "order_list");

       Integer status = null;
       if (!StringUtils.isEmpty(request.getParameter("status"))) {
           status = Integer.parseInt(request.getParameter("status"));
           model.addAttribute("status", status);
       }
       String orderId = request.getParameter("orderId");

       Integer pageIndex = 1;
       Integer pageSize = DataConfigObject.getInstance().getPageSize();

       if (!StringUtils.isEmpty(request.getParameter("page"))) {
           pageIndex = Integer.parseInt(request.getParameter("page"));
       }
       String mobile = "";
       if (!StringUtils.isEmpty(request.getParameter("mobile"))) mobile = request.getParameter("mobile");
       model.addAttribute("mobile", mobile);

       String startTime = "";
       if (!StringUtils.isEmpty(request.getParameter("startTime"))) {
           startTime = request.getParameter("startTime");
           model.addAttribute("startTime", startTime);
           startTime = startTime + " 00:00:00";
       }
       String endTime = "";
       if (!StringUtils.isEmpty(request.getParameter("endTime"))) {
           endTime = request.getParameter("endTime");
           model.addAttribute("endTime", endTime);
           endTime = endTime + " 23:59:59";
       }

       Integer developerId = 0;
       if (!StringUtils.isEmpty(request.getParameter("developerId"))) {
           developerId = Integer.parseInt(request.getParameter("developerId"));
       }

       //查询订单
       var result = tmallOrderService.getList(pageIndex, pageSize, orderId, status, shopId, mobile,developerId, startTime, endTime);
       model.addAttribute("pageIndex", pageIndex);
       model.addAttribute("pageSize", pageSize);
       model.addAttribute("totalSize", result.getTotalSize());
       model.addAttribute("lists", result.getList());

//       model.addAttribute("view", "taoorder");
//       model.addAttribute("pView", "tao");
       CommonControllerUtils.setViewKey(model,manageUserService,"taoorder");
       model.addAttribute("company", expressCompanyService.getExpressCompany());
       return "order/tao/order_list_tao";
   }

   /**
    * 订单详情（淘系）
    *
    * @param model
    * @param id
    * @param shopId
    * @param request
    * @return
    */
   @RequestMapping(value = "/order_detail", method = RequestMethod.GET)
   public String orderDetailTmall(Model model, @RequestParam Long id, @RequestParam Integer shopId, HttpServletRequest request) {

       DcTmallOrderEntity orderDetail = tmallOrderService.getOrderDetailAndItemsById(id);

       model.addAttribute("orderVo", orderDetail);

       //查询店铺信息
       var shop = shopService.getShop(shopId);
       model.addAttribute("shop", shop);
       model.addAttribute("menuId", "order_list");
       
       model.addAttribute("view", "taoorder");
       model.addAttribute("pView", "tao");
       return "v3/order_detail_tao";
   }

   /**
    * 确定订单
    * @param model
    * @param orderId
    * @param request
    * @return
    */
   @RequestMapping(value = "/order_confirm", method = RequestMethod.GET)
   public String orderConfirmGet(Model model, @RequestParam Long orderId,HttpServletRequest request) {
       var order = tmallOrderService.getOrderEntityById(orderId);
       if (order == null) {
           model.addAttribute("error", "没有找到订单");
           model.addAttribute("orderVo", new DcTmallOrderEntity());

       } else {
           model.addAttribute("orderVo", order);
//            model.addAttribute("clientId", order.getClientUserId() != null ? order.getClientUserId() : 0);
       }

//        model.addAttribute("clientId",181);

//        model.addAttribute("orderVo", service.getOrderConfirm(id, ErpOrderSourceEnum.TMALL));
        model.addAttribute("view", "taoorder");
       model.addAttribute("pView", "tao");
       return "tao/order_confirm_tao";
   }

   /**
    * 订单确认（进入仓库）
    *
    * @param req
    * @return
    */
   @ResponseBody
   @RequestMapping(value = "/order_confirm_post", method = RequestMethod.POST)
   public ApiResult<String> confirmOrder(@RequestBody OrderConfirmReq req, HttpServletRequest request) {
       if (req.getOrderId() == null || req.getOrderId() <= 0)
           return new ApiResult<>(ApiResultEnum.ParamsError.getIndex(), "参数错误，缺少orderId");

//        if (req.getClientId() == null || req.getOrderId() <= 0)
//            return new ApiResult<>(ApiResultEnum.ParamsError.getIndex(), "参数错误，缺少clientId");

       if (StringUtils.isEmpty(req.getReceiver()))
           return new ApiResult<>(ApiResultEnum.ParamsError.getIndex(), "参数错误，缺少receiver");
       if (StringUtils.isEmpty(req.getMobile()))
           return new ApiResult<>(ApiResultEnum.ParamsError.getIndex(), "参数错误，缺少mobile");
       if (StringUtils.isEmpty(req.getAddress()))
           return new ApiResult<>(ApiResultEnum.ParamsError.getIndex(), "参数错误，缺少address");


       //查询订单信息
       var order = tmallOrderService.getOrderEntityById(req.getOrderId());

       log.info("/**********************订单状态判断" + order.getStatus() + "**********************/");

       if (order == null)
           return new ApiResult<>(404, "订单不存在");//检查是否已经确认
       else if (order.getAuditStatus().intValue() > 0)
           return new ApiResult<>(501, "订单已经确认过了");
       else if (order.getStatus() != EnumTmallOrderStatus.WAIT_SEND_GOODS.getStatus())
           return new ApiResult<>(402, "订单不是发货中的状态，不能操作");

//        if (StringUtils.isEmpty(order.getContactPerson())) {
//            return new ApiResult<>(408, "订单缺少收货人信息，请补全收货人信息");
//        }

       //查询订单item信息
       List<DcTmallOrderItemEntity> items = tmallOrderService.getOrderItemsByOrderId(req.getOrderId());
       for (var item : items) {
           if (item.getRefundStatusStr().equalsIgnoreCase("NO_REFUND") == false) {
               return new ApiResult<>(401, "子订单处于退款状态，不能确认");
           }
       }


       log.info("/**********************开始确认订单" + req.getOrderId() + "**********************/");
       synchronized (this) {
           //确认订单，加入到仓库系统待发货订单列表
           ResultVo<Integer> result = tmallOrderService.orderConfirmAndJoinDeliveryQueueForTmall(req.getOrderId(), 0, req.getReceiver(), req.getMobile(), req.getAddress(), req.getSellerMemo());
//            if (result.getCode() == 0 && data.getInt("orderType") > -1 && data.getInt("buyUserId") > 0) {
//                ResultVo<Integer> resultSub = tmallOrderService.addTmallOrderByDeveLoper(order, data.getInt("buyUserId"), data.getInt("orderType"), ErpOrderSourceEnum.TMALL);
//                return new ApiResult<>(resultSub.getCode(), resultSub.getMsg());
//            }
           log.info("/**********************确认订单完成" + result + "**********************/");
           return new ApiResult<>(result.getCode(), result.getMsg());
       }
   }

   /**
    * 创建订单
    * @param model
    * @param shopId
    * @param request
    * @return
    */
   @RequestMapping("/order_create")
   public String orderCreate(Model model,@RequestParam Integer shopId, HttpServletRequest request){
       model.addAttribute("menuId", "order_create");
       model.addAttribute("shopId", shopId);
       model.addAttribute("view", "taoorder");
       model.addAttribute("pView", "tao");
       return "order/tao/order_create_tao";
   }

   /**
    * pdd创建订单
    * @param model
    * @param request
    * @return
    */
   @RequestMapping(value = "/order_create", method = RequestMethod.POST)
   public String postSystemOrder(Model model, HttpServletRequest request) {
       model.addAttribute("menuId", "order_create");
       Integer shopId=Integer.parseInt(request.getParameter("shopId"));
       /***商品信息****/
       String[] specNumber = request.getParameterValues("specNumber");//规格编码组合
       String[] goodsNumber = request.getParameterValues("goodsNumber");//商品编码组合
       String[] goodsId = request.getParameterValues("goodsId");//商品id组合
       String[] specsId = request.getParameterValues("specId");//商品规格id组合
       String[] quantitys = request.getParameterValues("quantity");//数量组合
       String[] prices = request.getParameterValues("note");//商品价格

       String orderNumber = request.getParameter("orderNumber");
       //收件人信息
       String contactMobile = request.getParameter("contactMobile");
       String contactPerson = request.getParameter("contactPerson");
       String area = request.getParameter("area");
       String address = request.getParameter("address");
       String shippingFee= StringUtils.isEmpty(request.getParameter("shippingFee")) ? "0" :request.getParameter("shippingFee");
       String sellerMemo = request.getParameter("sellerMemo");

       String[] areaNameArray = area.split(" ");

       String provinceName = "";
       if (areaNameArray.length > 0) provinceName = areaNameArray[0];
       String cityName = "";
       if (areaNameArray.length > 1) cityName = areaNameArray[1];
       String districtName = "";
       if (areaNameArray.length > 2) districtName = areaNameArray[2];

       DcTmallOrderEntity order = new DcTmallOrderEntity();
       List<DcTmallOrderItemEntity> items = new ArrayList<>();
       double goodsTotalAmount = 0;//商品总价
       for (int i = 0,n=goodsId.length;i<n;i++) {
           if(StringUtils.isEmpty(goodsId[i]))continue;
           DcTmallOrderItemEntity taoOrderItem = new DcTmallOrderItemEntity();
           Integer specId=Integer.parseInt(specsId[i]);
           BigDecimal price = new BigDecimal(prices[i]);
           Integer count =Integer.parseInt(quantitys[i]);
           var spec = erpGoodsService.getSpecBySpecId(specId);

           goodsTotalAmount +=  price.doubleValue() * count;

           taoOrderItem.setErpGoodsId(spec.getGoodsId());
           taoOrderItem.setErpGoodsSpecId(spec.getId());
           taoOrderItem.setProductImgUrl(spec.getColorImage());
           taoOrderItem.setGoodsTitle(spec.getGoodTitle());
           taoOrderItem.setGoodsNumber(goodsNumber[i]);
           taoOrderItem.setPrice(new BigDecimal(price.doubleValue()));
           taoOrderItem.setSpecNumber(specNumber[i]);
           taoOrderItem.setQuantity(count.doubleValue());
           taoOrderItem.setSkuInfo(spec.getColorValue()+","+spec.getSizeValue());
           taoOrderItem.setSubItemId(orderNumber);
           taoOrderItem.setRefundStatusStr("NO_REFUND");
           taoOrderItem.setRefundStatus(0);
           taoOrderItem.setItemAmount(new BigDecimal(price.doubleValue() * count));
           items.add(taoOrderItem);
       }
       order.setItems(items);
       double orderTotalAmount=goodsTotalAmount+Double.valueOf(shippingFee);
       order.setId(orderNumber);
       order.setCreateTime(new Date());
       order.setModifyTime(new Date());
       order.setPayTime(new Date());
       order.setTotalAmount(new BigDecimal(orderTotalAmount));
       order.setShippingFee(new BigDecimal(shippingFee));
       order.setPayAmount(new BigDecimal(orderTotalAmount));
       order.setBuyerName("");
       order.setSellerMemo(sellerMemo);
       order.setProvince(provinceName);
       order.setCity(cityName);
       order.setArea(districtName);
       order.setAddress(new StringBuilder(provinceName).append(cityName).append(districtName).append(address).toString());
       order.setStatus(EnumTmallOrderStatus.WAIT_SEND_GOODS.getStatus());
       order.setStatusStr(EnumTmallOrderStatus.WAIT_SEND_GOODS.getName());
       order.setContactPerson(contactPerson);
       order.setMobile(contactMobile);

       var result = tmallOrderService.updateTmallOrderForOpenTaobao(shopId, order);
       if(result.getCode()==0){
           return "redirect:/tao/order_list?shopId="+shopId;
       }
       return "redirect:/tao_order/order_create?shopId=" + shopId;

   }

   /**
    * 退货单详情
    *
    * @param model
    * @param request
    * @return
    */
   @RequestMapping(value = "/refund_apply", method = RequestMethod.GET)
   public String refundApply(Model model, @RequestParam Integer shopId, @RequestParam Long id, HttpServletRequest request) {
       //查询店铺信息
       DcTmallOrderEntity orderDetail = tmallOrderService.getOrderDetailAndItemsById(id);

       model.addAttribute("orderVo", orderDetail);

       //查询店铺信息
       var shop = shopService.getShop(shopId);
       model.addAttribute("shop", shop);
       model.addAttribute("menuId", "order_list");
       model.addAttribute("view", "taoorder");
       model.addAttribute("pView", "tao");

       return "refund/order_refund_apply_tao";
   }


   @ResponseBody
    @RequestMapping(value = "/order_list_export", method = RequestMethod.GET)
    public void purchasePutDetail(Model model, HttpServletRequest request, HttpServletResponse response) {
        Integer shopId = null;
        if (!StringUtils.isEmpty(request.getParameter("shopId"))) {
            shopId = Integer.parseInt(request.getParameter("shopId"));
        }
        Integer status = null;
        if (!StringUtils.isEmpty(request.getParameter("status"))) {
            status = Integer.parseInt(request.getParameter("status"));
        }
        String mobile = "";
        if (!StringUtils.isEmpty(request.getParameter("mobile"))) mobile = request.getParameter("mobile");

        String startTime = "";
        if (!StringUtils.isEmpty(request.getParameter("startTime"))) {
            startTime = request.getParameter("startTime");
            startTime = startTime + " 00:00:00";
        }
        String endTime = "";
        if (!StringUtils.isEmpty(request.getParameter("endTime"))) {
            endTime = request.getParameter("endTime");
            endTime = endTime + " 23:59:59";
        }
 
 
        //查询订单
        var result = tmallOrderService.getList(1, 1000, null, status, shopId, mobile,0, startTime, endTime);
        var lists = result.getList();

        /***************根据店铺查询订单导出的信息*****************/
        String fileName = "taobao_order_list_";//excel文件名前缀
        //创建Excel工作薄对象
        HSSFWorkbook workbook = new HSSFWorkbook();

        //创建Excel工作表对象
        HSSFSheet sheet = workbook.createSheet();
        HSSFRow row = null;
        HSSFCell cell = null;
        //第一行为空
        row = sheet.createRow(0);
        cell = row.createCell(0);
        cell.setCellValue("");
        cell = row.createCell(0);
        cell.setCellValue("订单编号");
        cell = row.createCell(1);
        cell.setCellValue("商品标题");
        cell = row.createCell(2);
        cell.setCellValue("规格");
        cell = row.createCell(3);
        cell.setCellValue("数量");
        cell = row.createCell(4);
        cell.setCellValue("收货人姓名");
        cell = row.createCell(5);
        cell.setCellValue("收货人电话");
        cell = row.createCell(6);
        cell.setCellValue("收货人地址");
        cell = row.createCell(7);
        cell.setCellValue("备注");
        cell = row.createCell(8);
        cell.setCellValue("物流公司");
        cell = row.createCell(9);
        cell.setCellValue("物流单号");


        int currRowNum = 0;
        HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
        // 循环写入数据
        for (int i = 0; i < lists.size(); i++) {
            currRowNum++;
            //写入订单
            DcTmallOrderEntity order = lists.get(i);
            //创建行
            row = sheet.createRow(currRowNum);
            cell = row.createCell(0);
            cell.setCellValue(order.getId().toString());
            //商品名称
            cell = row.createCell(1);
            String goodsName="";
            String spec="";
            String num="";
            for (var item : order.getItems()) {
                goodsName += item.getGoodsTitle()+"|";
                spec += item.getSkuInfo()+"|";
                num += item.getQuantity().intValue() + "|";
            }
           
            goodsName = goodsName.substring(0,goodsName.length()-1);
            spec = spec.substring(0,spec.length()-1);
            num = num.substring(0,num.length()-1);
            

            cell.setCellValue(goodsName);
            cell = row.createCell(2);
            cell.setCellValue(spec);
            cell = row.createCell(3);
            cell.setCellValue(num);
            //收货人
            cell = row.createCell(4);
            cell.setCellValue(order.getContactPerson());
            cell = row.createCell(5);
            cell.setCellValue(order.getMobile());
            cell = row.createCell(6);
            cell.setCellValue(order.getAddress());
            String remark = order.getBuyerFeedback() + order.getSellerMemo();
            cell = row.createCell(7);
            cell.setCellValue(remark);

        }
        response.reset();
        response.setContentType("application/msexcel;charset=UTF-8");
        try {
            SimpleDateFormat newsdf = new SimpleDateFormat("yyyyMMdd");
            String date = newsdf.format(new Date());
            response.addHeader("Content-Disposition", "attachment;filename=\""
                    + new String((fileName + date + ".xls").getBytes("GBK"),
                    "ISO8859_1") + "\"");
            OutputStream out = response.getOutputStream();
            workbook.write(out);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            JOptionPane.showMessageDialog(null, "导出失败!");
            e.printStackTrace();
        } catch (IOException e) {
            JOptionPane.showMessageDialog(null, "导出失败!");
            e.printStackTrace();
        }
    }

}
